<?php

namespace App\Http\Controllers\Api\V1\Auth;

use App\Http\Controllers\BaseController;
use App\Http\Requests\Api\V1\Auth\AuthRequest;
use App\Models\Auth\Authorization;
use App\Models\Customer\Customer;
use App\Models\Wechat;
use App\Transformers\Auth\AuthorizationTransformer;
use App\Transformers\Frontend\CustomerTransformer;
use App\Tyt\Manager\Wechat\WechatManager;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class AuthorizationController extends BaseController
{
    public function login(AuthRequest $request)
    {
        $attributes = $request->validated();
//        $token = $this->localLogin();
        $token = $attributes['auth_type'] === Customer::AUTH_WE_CHAT ? $this->authWeChat($attributes) : $this->authTel($attributes);
        $authorization = new Authorization();
        $authorization->setAttribute('token', $token);
        return $this->response->item($authorization, new AuthorizationTransformer());
    }

    private function authTel(array $attributes)
    {
        $credentials = ['tel' => $attributes['tel'], 'password' => $attributes['password']];
        if (!$token = auth('customer')->attempt($credentials)) {
            throw new UnauthorizedHttpException('invalid_credentials', '用户名或密码错误');
        }
        return $token;
    }

    private function authWeChat(array $attributes)
    {
        $config = Wechat::first();
        $wechat = new WechatManager($config, $attributes);
        $wechat->init();
        $customer = $wechat->oauth()->save();
        if (!$token = auth('customer')->login($customer)) {
            throw new UnauthorizedHttpException('invalid_credentials', '微信授权失败');
        }
        return $token;
    }

    private function localLogin()
    {
        $customer = Customer::find(2);
        if (!$token = auth('customer')->login($customer)) {
            throw new UnauthorizedHttpException('invalid_credentials', '微信授权失败');
        }
        return $token;
    }

    public function current()
    {
        $customer = auth('customer')->user();
        if (!$customer) {
            throw new UnauthorizedHttpException('invalid_credentials', '未登录');
        }
        return $this->response->item($customer, new CustomerTransformer());
    }
}
